package br.unifacs.mda.plugin.main.popup.actions;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

import br.unifacs.mda.plugin.transformation.uml2java.ATLTransformUML2JAVA;
import br.unifacs.mda.plugin.util.Messages;

public class GeneratePSMJavaAction implements IObjectActionDelegate {

	private Shell shell;
	private IFile pimFile;
	private IProject project;

	/**
	 * Constructor for Action1.
	 */
	public GeneratePSMJavaAction() {
		super();
	}

	/**
	 * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
	 */
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		shell = targetPart.getSite().getShell();

		IStructuredSelection sel = (IStructuredSelection) targetPart.getSite()
				.getSelectionProvider().getSelection();
		this.pimFile = (IFile) sel.getFirstElement();
		this.project = this.pimFile.getProject();
	}

	/**
	 * @see IActionDelegate#run(IAction)
	 */
	public void run(IAction action) {
		String outFilePath = this.pimFile.getParent().getLocation().toString()
				+ "/" + this.project.getName() + ".psmJava";
		ATLTransformUML2JAVA transformation = ATLTransformUML2JAVA
				.getInstance();
		transformation.pim2psm(this.pimFile.getLocation().toString(),
				outFilePath);

		try {
			this.project.refreshLocal(IResource.DEPTH_INFINITE, null);		
		} catch (CoreException e) {
			e.printStackTrace();
		}
		MessageDialog.openInformation(shell, "MDA Plug-in",
				Messages.PSM_GERADO_SUCESSO);

	}

	/**
	 * @see IActionDelegate#selectionChanged(IAction, ISelection)
	 */
	public void selectionChanged(IAction action, ISelection selection) {
	}

}
